const express = require("express");
const app = express();
const cors = require("cors");
const Joi = require("joi");
app.use(cors());

const multer = require("multer");
const upload = multer({ dest: "./public/upload" });
app.use(upload.any());
app.use(express.static("./public"));

const bodyParser = require("body-parser");
//解析 JSON 请求体中的数据
app.use(bodyParser.json());
//解析 URL 编码的请求体中的数据
app.use(bodyParser.urlencoded({ extended: false }));
// 一定要在路由之前，封装 res.cc 函数
app.use((req, res, next) => {
  // status 默认值为 1，表示失败的情况
  // err 的值，可能是一个错误对象，也可能是一个错误的描述字符串
  res.cc = (err, status = 1) => {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});
// 错误中间件
app.use((err, req, res, next) => {
  if (err instanceof Joi.ValidationError) return res.cc(err);
})

const user = require("./router/login");
app.use("/api", user);
const userinfo = require("./router/userinfo");
app.use("/user", userinfo);
const setting = require("./router/setting");
app.use("/set", setting);

app.get("/", (req, res) => res.send("Hello World!"));

app.listen(3000, () => console.log(`http://127.0.0.1:3000`));
